import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { NativeAudio } from '@ionic-native/native-audio';
//import { Vibration } from '@ionic-native/vibration';
import { ContactPage } from '../contact/contact';
import { HomePage } from '../home/home';
import { SearchPage } from '../search/search';
import { RestService } from '../../app/services/rest.service';
import { TranslateService } from '@ngx-translate/core';

import * as _ from 'lodash';

@Component({
  selector: 'page-person',
  templateUrl: 'person.html'
})
export class PersonPage {
  user: any;
  filter: any;
  persons: any[];
  tmpPersons: any[];
  mutedIds = [];
  interval: any;
  searchText = '';
  audioId = 'alarmAudio';
  audioId2 = 'alarmAudio2';

  allPersons = [];
  pNumberPerPage = 10;
  position = 0;

  constructor(public navCtrl: NavController,
              private rest: RestService,
              private nativeAudio: NativeAudio,
              //private vibration: Vibration,
              private translate: TranslateService) {
    this.user = this.rest.getUser();
    this.persons = [];
  }

  loadAudio() {
    this.nativeAudio.preloadSimple(this.audioId, 'assets/sound/alarm01.wav').then(() => {
      console.log('Audio file was loaded!');
    }, (error) => {
      console.error('Failed to load audo file - ' + error);
    });
    this.nativeAudio.preloadSimple(this.audioId2, 'assets/sound/alarm02.wav').then(() => {
      console.log('Audio file was loaded!');
    }, (error) => {
      console.error('Failed to load audo file - ' + error);
    });
  }

  nav2home(person) {
    this.navCtrl.push(HomePage, {
      person: person,
      persons: this.allPersons
    });
  }

  getBedString(person) {
    if (person.bedString) {
      return person.bedString.replace(/##/g, ' - ');
    } else {
      return '';
    }
  }

  getAlarmString(person, alarm) {
    let alarmString = '<span class="' + ((person['hide' + _.capitalize(alarm) + 'Alarm'] || !this.getAlarmTypeEnableStatus(person, alarm)) ? 'acked' : 'unacked') + '">';
    alarmString += this.translate.get(alarm)['value'] + '</span>';
    return alarmString;
  }

  getAlarmTypeEnableStatus(person, alarm) {
    if (alarm !== 'UP' && alarm !== 'SIDE' && alarm !== 'AWAY') {
      return true;
    }

    return person[alarm.toLowerCase() + 'Alarm'];
  }

  getAlarmsInArray(person) {
    const alarms = [];

    if (person.deviceAlarmFlag) {
      alarms.push('DEVICE');
    }

    if (person.awayAlarmFlag) {
      alarms.push('AWAY');
    }

    if (person.wetAlarmFlag) {
      alarms.push('WET');
    }

    if (person.sideAlarmFlag) {
      alarms.push('SIDE');
    }

    if (person.upAlarmFlag) {
      alarms.push('UP');
    }

    if (person.heartAlarmFlag) {
      alarms.push('HEART');
    }

    if (person.breatheAlarmFlag) {
      alarms.push('BREATHE');
    }

    if (person.moveAlarmFlag) {
      alarms.push('MOVE');
    }

    if (person.ringAlarmFlag) {
      alarms.push('RING');
    }

    if (person.turnOverReminderAlarmFlag) {
      alarms.push('TURN_OVER');
    }

    return alarms;
  }

  getAlarms(person) {
    const alarms = this.getAlarmsInArray(person);

    if (alarms.length < 1) {
      return this.translate.get('normal')['value'];
    } else {
      const alarmStrings = [];
      alarms.forEach(alarm => {
        alarmStrings.push(this.getAlarmString(person, alarm));
      });
      return alarmStrings.join('<span>,&nbsp;</span>');
    }
  }

  hasActiveAlarm(person) {
    const alarms = this.getAlarmsInArray(person);
    if (alarms.length < 1) {
      return false;
    }

    for (let i = 0; i < alarms.length; i++) {
      if (person['hide' + _.capitalize(alarms[i]) + 'Alarm'] || !this.getAlarmTypeEnableStatus(person, alarms[i])) {
        continue;
      } else {
        return true;
      }
    }

    return false;
  }

  getItems(event) {
    const value = event.target.value;
    if (value && value.trim() != '') {
      this.searchText = value.trim();
    } else {
      this.searchText = '';
    }
  }

  nav2contact() {
    this.navCtrl.push(ContactPage, {
      persons: this.allPersons
    });
  }

  nav2search() {
    this.navCtrl.push(SearchPage, {});
  }

  initData() {
    if (!this.searchText) {
      this.rest.getWithParams('/data/person/search/monitorAllIn', {
        institutionId: this.user.instId,
        checkoutTime: 1
      }).subscribe(resp => {
        this.applyFilter(resp['_embedded']['persons']);
        this.playAudio();
      }, message => {
        console.error('Failed to get all persons in: ' + message);
      });
    } else {
      this.rest.getWithParams('/data/person/search/monitorNamein', {
        institutionId: this.user.instId,
        checkoutTime: 1,
        name: this.searchText
      }).subscribe(resp => {
        this.applyFilter(resp['_embedded']['persons']);
        this.playAudio();
      }, message => {
        console.error('Failed to get all persons in: ' + message);
      });
    }
  }

  toggleMute(person) {
    const index = this.mutedIds.indexOf(person.id);
    if (index > -1) {
      // currently, it's muted, unmuted
      this.mutedIds.splice(index, 1);
    } else {
      // it's unmited, mute it
      this.mutedIds.push(person.id);
    }
  }

  isMuted(person) {
    return this.mutedIds.indexOf(person.id) > -1;
  }

  playAudio() {
    for (let i = 0; i < this.persons.length; i++) {
      if (!this.isMuted(this.persons[i]) && this.hasActiveAlarm(this.persons[i])) {
        this.doPlay();
        return;
      }
    }
  }

  doPlay() {
    // this.vibration.vibrate(1000);
    this.nativeAudio.play(this.audioId).then(() => {
    }, error => {
      console.log('Failed to play audio - ' + error);
    });
  }

  applyFilter(items) {
    this.tmpPersons = [];
    this.allPersons = [];

    if (this.filter.persons.length > 0) {
      this.filter.persons.forEach(person => {
        const index = _.findIndex(items, {id: person.id});
        if (index > -1) {
          this.allPersons.push(items[index]);
        }
      });
      this.assignInitials();
      return;
    }

    if (this.filter.nurses.length > 0) {
      items.forEach(person => {
        const index = _.findIndex(this.filter.nurses, {id: person.nurseId});
        if (index > -1) {
          this.allPersons.push(person);
        }
      });
      this.assignInitials();
      return;
    }

    if (this.filter.rooms.length > 0) {
      items.forEach(person => {
        if (person.bedString) {
          const beds = person.bedString.split('##')
          if (beds.length > 2) {
            const match = beds[0] + '##' + beds[1] + '##' + beds[2];
            const index = _.findIndex(this.filter.rooms, {match: match});
            if (index > -1) {
              this.allPersons.push(person);
            }
          }
        }
      });
      this.assignInitials();
      return;
    }

    if (this.filter.levels.length > 0) {
      items.forEach(person => {
        if (person.bedString) {
          const beds = person.bedString.split('##')
          if (beds.length > 1) {
            const match = beds[0] + '##' + beds[1]
            const index = _.findIndex(this.filter.levels, {match: match});
            if (index > -1) {
              this.allPersons.push(person);
            }
          }
        }
      });
      this.assignInitials();
      return;
    }

    if (this.filter.buildings.length > 0) {
      items.forEach(person => {
        if (person.bedString) {
          const beds = person.bedString.split('##')
          if (beds.length > 0) {
            const match = beds[0];
            const index = _.findIndex(this.filter.buildings, {match: match});
            if (index > -1) {
              this.allPersons.push(person);
            }
          }
        }
      });
      this.assignInitials();
      return;
    }

    this.allPersons = items;
    this.assignInitials();
  }

  getFilterClass() {
    if (!this.filter || _.isEmpty(this.filter)) {
      return 'no-filter';
    }

    if (this.filter.persons.length === 0 &&
        this.filter.nurses.length === 0 &&
        this.filter.buildings.length === 0 &&
        this.filter.levels.length === 0 &&
        this.filter.rooms.length === 0) {
        return 'no-filter';
    }

    return 'with-filter';
  }

  assignInitials() {
    if (this.position > this.pNumberPerPage) {
      for (let i = 0; i < this.allPersons.length && i < this.position; i++) {
        this.tmpPersons.push(this.allPersons[i]);
      }
    } else {
      for (let i = 0; i < this.allPersons.length && i < this.pNumberPerPage; i++) {
        this.tmpPersons.push(this.allPersons[i]);
        this.position = i + 1;
      }
    }

    // Remove un-qualified person from persons
    this.rest.updateArray(this.persons, this.tmpPersons);
    this.tmpPersons = [];
  }

  doInfinite(infiniteScroll) {
    setTimeout(() => {
      for (let i = this.position, j = 0; i < this.allPersons.length && j < this.pNumberPerPage; i++, j++) {
        this.persons.push(this.allPersons[i]);
        this.position = i + 1;
      }

      infiniteScroll.complete();
    }, 500);
  }

  ionViewDidEnter() {
    this.loadAudio();
    this.filter = this.rest.getFilter();
    this.initData();
    this.interval = setInterval(() => {
      this.initData();
    }, 3000);
  }

  ionViewWillLeave() {
    if (this.interval) {
      clearInterval(this.interval);
    }
    this.nativeAudio.unload(this.audioId).then(() => {}, () => {});
  }
}
